package com.alog.storage.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import com.alog.storage.Contants;
import com.alog.storage.StorageApplication;
import com.alog.storage.R;
import com.alog.storage.ui.dialog.LoadingDialog;
import com.alog.storage.ui.widget.NodataLayout;
import com.alog.storage.ui.widget.SlideBackLayout;
import com.alog.storage.utils.CommonUtil;

/**
 * Activity基类，所有Activity继承此类
 */
public abstract class BaseActivity extends FragmentActivity implements SlideBackLayout.SlideFinishListener, IBaseView {
    private NetworkChangeReceiver mNetworkChangeReceiver;
    private SlideBackLayout mRootLayout;
    private boolean mTouchClosed;
    protected Activity context;
    protected boolean isSlideBack = true;
    protected NodataLayout nodataView;
    protected View dataView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(R.anim.push_right_to_left, R.anim.push);
        super.onCreate(savedInstanceState);
        context = this;
        mTouchClosed = false;
        if (this.getClass().getSimpleName().equals(MainTabActivity.class.getSimpleName())) {
            isSlideBack = false;
        }
        if (isSlideBack) {
            mRootLayout = new SlideBackLayout(this);
            mRootLayout.setSlideFinishListener(this);
            StorageApplication application = (StorageApplication) getApplication();
            mRootLayout.attachToActivity(this, application.bgBitmap);

        }
        //状态栏沉浸,4.4以上支持
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            Window window = getWindow();
//            // 透明状态栏
//            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
        registerNetworkChangeReceiver();
        StorageApplication.activityList.add(this);

    }

    public void setTouchMove(boolean touchMove) {
        mRootLayout.setTouchMove(touchMove);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        saveBg();
    }

    private void saveBg() {
        if (isSlideBack || this.getClass().getSimpleName().equals(MainTabActivity.class.getSimpleName())) {
            StorageApplication application = (StorageApplication) getApplication();
            application.setBgBitmap(CommonUtil.takeScreenShot(this));
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        saveBg();
    }

    private void registerNetworkChangeReceiver() {
        mNetworkChangeReceiver = new NetworkChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkChangeReceiver, filter);
    }

    private void unregisterNetworkChangeReceiver() {
        if (mNetworkChangeReceiver != null) {
            unregisterReceiver(mNetworkChangeReceiver);
        }
    }

    /**
     * 子类实现,网络连接成功时触发
     */
    public void networkAvailable() {
    }

    /**
     * 子类实现,网络断开时触发
     */
    public void networkUnAvailable() {
    }

    private Dialog mLoadingDlg;

    protected Dialog getLoadingDialog(boolean cancelable) {
        if (mLoadingDlg == null) {
            mLoadingDlg = LoadingDialog.createDialog(this, LoadingDialog.ProgressStyle.LOTTERY_COMMON, cancelable);
        }
        return mLoadingDlg;
    }

    /**
     * 显示加载框
     */
    public void loadDataStarted(String... msg) {
        if (!isFinishing()) {
            ((LoadingDialog) getLoadingDialog(true)).setLoadInfo(msg != null && msg.length > 0 ? msg[0] : "正在加载...");
            getLoadingDialog(true).show();
        }
    }

    /**
     * 取消加载框
     */
    public void loadDataComplete() {
        if (!isFinishing() && mLoadingDlg != null && mLoadingDlg.isShowing()) {
            mLoadingDlg.dismiss();
        }
    }

    public void showNoNetwork() {
        if (dataView != null && nodataView != null) {
            dataView.setVisibility(View.GONE);
            nodataView.setType(NodataLayout.TYPE_NO_NETWORK);
            nodataView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void login() {
        Intent i = new Intent();
        i.setClass(context, LoginActivity.class);
        startActivityForResult(i, Contants.ACTIVITY_CODE_LOGIN);
    }

    @Override
    public void showError() {
        if (dataView != null && nodataView != null) {
            dataView.setVisibility(View.GONE);
            nodataView.setType(NodataLayout.TYPE_SERVER_ERROR);
            nodataView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void showEmpty() {
        if (dataView != null && nodataView != null) {
            dataView.setVisibility(View.GONE);
            nodataView.setType(NodataLayout.TYPE_NO_DATA);
            nodataView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public <T> void setData(int apiId, T data) {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput();
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    protected void hideSoftInput() {
        if (this.getCurrentFocus() != null) {
            if (this.getCurrentFocus().getWindowToken() != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    public class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
            if (activeNetInfo != null) {
                networkAvailable();
            } else {
                networkUnAvailable();
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (!mTouchClosed) {
            overridePendingTransition(R.anim.push, R.anim.push_left_to_right);
        } else {
            overridePendingTransition(0, 0);
        }
        mTouchClosed = false;
    }

    @Override
    public void onFinish() {
        mTouchClosed = true;
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterNetworkChangeReceiver();
        StorageApplication.activityList.remove(this);
        StorageApplication application = (StorageApplication) getApplication();
        application.clearBgBitmap();
    }

}
